/*
 * Copyright 2002-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package mytest.tx.mutithreads;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @author zenghua233
 * @since 4.2.1
 */
@Service("mutithreadsService")
public class MutithreadsServiceImpl implements MutithreadsService {
	@Autowired
	private MutithreadsDao mutithreadsDao;
	
	public CountDownLatch latch = new CountDownLatch(10);

	/**
	 * 嵌套注解参考spring文档《Multiple Transaction Managers with @Transactional》
	 */
	//支持jee的这几个注解不？ TODO
	@Transactional
	@Override
	public void saveData() {
		ExecutorService executor = Executors.newFixedThreadPool(10);
		for (int i = 0; i < 10; i++) {
			executor.execute(new SaveTask(latch, i));
		}
		
		try {
			//一直等待线程池执行完
			latch.await();
			Thread.sleep(1000);
		}
		catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		//可以回滚
//		this.insertData(0);
	}

	//REQUIRES_NEW在同一个类中是无效的，因为都是在同一个类类加载器，线程一样的
	@Transactional(propagation=Propagation.NESTED)
	@Override
	public void insertData(int i) {
		mutithreadsDao.insert();
		System.out.println("执行" + i + "次写入");
		if (i == 5) {
			throw new RuntimeException();
		}
	}
	
	class SaveTask implements Runnable {
		private CountDownLatch latch;
		private int num;
		
		public SaveTask(CountDownLatch latch, int num) {
			this.latch = latch;
			this.num = num;
		}
		
		@Override
		public void run() {
			//这里相当于this.insertData()，JdkDynamicAopProxy里面创建的，没有走代理对象，所以该方法上面使用@Transactional是无效的
			insertData(num);
			latch.countDown();
		}
	}
}
